<template>
  <!-- 列表设置 -->
  <el-dialog
    :model-value="dialogTableVisible"
    title="列表设置"
    top="2vh"
    :draggable="true"
    :destroy-on-close="true"
    @close="onCancel"
    :close-on-click-modal="false"
    :align-center="true"
  >
    <div v-loading="loading" element-loading-text="加载中...">
      <div class="header_Table"
        ><span
          @click="onClickTitleIndex(1)"
          class="title_xy"
          :class="onTitleIndex == 1 ? 'title_color' : ''"
          >表头字段</span
        ><span
          @click="onClickTitleIndex(2)"
          class="title_xy"
          :class="onTitleIndex == 2 ? 'title_color' : ''"
          >列表排序</span
        ></div
      >
      <div v-if="onTitleIndex == 1">
        <section class="list_option">
          <span
            class="item_option"
            v-for="(item, index) in optionsHeader"
            @click="onClickoptionsHeader(index)"
            :key="index"
            >{{ item }}</span
          >
          <el-popover
            @before-enter="popoverShow"
            ref="popover"
            placement="left-end"
            title="操作"
            :width="300"
            trigger="click"
          >
            <template #reference>
              <span class="item_option">移到</span>
            </template>
            <div style="display: flex; justify-content: end; align-items: center">
              <span
                @click="onClickoptionsHeader(6)"
                style="color: #007cff; cursor: pointer; margin-right: 12px"
                >首行</span
              >
              <span
                @click="onClickoptionsHeader(7)"
                style="color: #007cff; cursor: pointer; margin-right: 12px"
                >末尾</span
              >
            </div>
            <div style="display: flex; align-items: center; margin: 16px 0 12px">
              <span style="margin-right: 12px">移动到</span
              ><el-input-number
                placeholder="行"
                v-model="numInput"
                :min="1"
                :max="HeaderDataList.length"
              /><el-button
                @click="onClickoptionsHeader(8)"
                color="#007cff"
                style="height: 30px; margin-left: 12px"
                >确认</el-button
              >
            </div>
          </el-popover>
        </section>
        <el-table
          ref="multipleTableRef"
          :data="HeaderDataList"
          height="500"
          row-key="id"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40" />
          <el-table-column type="index" label="序号" width="50" />
          <el-table-column property="initFieldName" label="表头名称" width="130" />
          <el-table-column label="自定义表头名称" width="180">
            <template v-slot="i">
              <el-input placeholder="可修改名称" v-model="i.row.name"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="显示列" width="130">
            <template v-slot="i">
              <el-switch
                v-model="i.row.showColumn"
                :active-text="i.row.showColumn ? '显示' : '隐藏'"
              />
            </template>
          </el-table-column>
          <el-table-column label="冻结列" width="130">
            <template v-slot="i">
              <el-switch
                v-model="i.row.freezeColumn"
                :active-text="i.row.freezeColumn ? '冻结' : '不冻结'"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template v-slot="i">
              <!--  @mousedown="fieldSort($event, i.$index)" -->
              <el-icon
                draggable="true"
                @dragenter="dragenter($event, i.$index)"
                @dragend="dragend(i.$index)"
                @dragover="dragover($event)"
                style="
                  display: flex;
                  width: 100%;
                  align-items: center;
                  justify-content: center;
                  cursor: move;
                  height: 100%;
                "
                size="16"
              >
                <Sort />
              </el-icon>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="onTitleIndex == 2">
        <section class="list_option">
          <span
            class="item_option"
            v-for="(item, index) in optionsTable"
            :key="index"
            @click="onClickoptionsTableData(index)"
            >{{ item }}</span
          >
        </section>
        <el-table :data="TableDataList" height="500" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="40" />
          <el-table-column type="index" label="序号" fixed="left" min-width="50" />
          <el-table-column property="name" label="工单状态" width="140">
            <template v-slot="i">
              {{ typeState.filter((o) => i.row.type == o.type)[0].name }}
            </template>
          </el-table-column>
          <el-table-column label="条件" align="center">
            <template v-slot="i">
              <el-select v-model="i.row.orderByField" placeholder="Select" style="width: 80%">
                <el-option
                  v-for="(item, index) in options"
                  :key="index"
                  :label="item"
                  :value="index + 1"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="排序" align="center">
            <template v-slot="i">
              <el-select v-model="i.row.orderBy" placeholder="Select" style="width: 70%">
                <el-option label="升序" :value="1" />
                <el-option label="倒序" :value="2" />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onCancel">取消</el-button>
        <el-button color="#007cff" v-if="onTitleIndex == 1" type="primary" @click="onSave(1)">
          确定</el-button
        >
        <el-button color="#007cff" v-else type="primary" @click="onSave(2)"> 确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
  import { ref, toRefs, watch } from 'vue'
  import {
    orderBySave,
    getOrderTableOrderByField,
    workTableFieldSave,
    getOrderTableField,
    getOrderTableInitField,
    getOrderTableInitOrderByField,
  } from '../api/order'
  import { ElMessage } from 'element-plus'
  const props = defineProps({
    dialogTableVisible: Boolean,
    type: Number,
  })
  const { dialogTableVisible, type } = toRefs(props)
  const emits = defineEmits(['set-table-dialog', 'update-list'])
  const loading = ref(false)
  const HeaderDataList = ref([])
  const TableDataList = ref([])
  const onTitleIndex = ref(1)
  const numInput = ref() //输入的数字
  const popover = ref()
  const multipleTableRef = ref()
  const arrSelection = ref([]) //选择列表数据
  const options = ref(['更新时间', '创建时间', '完成时间', '取消时间'])
  const optionsHeader = ref(['恢复默认', '全部显示', '全部冻结', '全部解冻', '上移', '下移'])
  const optionsTable = ref(['恢复默认', '升序', '降序'])
  const typeState = ref([
    { name: '全部工单', type: 1 },
    { name: '待派单', type: 2 },
    { name: '处理中', type: 3 },
    { name: '已完成', type: 4 },
    { name: '已取消', type: 5 },
    { name: '待结单', type: 50 },
  ])
  // 点击选择弹窗里的选项卡
  const onClickTitleIndex = (n) => {
    onTitleIndex.value = n
  }
  // 1表头 2列表
  watch(onTitleIndex, (n) => {
    arrSelection.value = []
    switch (n) {
      case 1:
        getHeaderDataList()
        break
      case 2:
        getTableDataList()
        break
    }
  })
  // 弹窗
  watch(dialogTableVisible, (val) => {
    if (val) {
      onTitleIndex.value = 1
      getHeaderDataList()
    }
  })
  const onCancel = () => {
    emits('set-table-dialog', false)
  }

  // 获取工单表头字段设置项
  const getHeaderDataList = async () => {
    loading.value = true
    await getOrderTableField(type.value).then((res) => {
      if (res) {
        HeaderDataList.value = res.data.data.rows.map((o, index) => {
          return { ...o, sort: index, admFactoryOrderTableFieldId: o.admOrderTableFieldId }
        })
      }
    })
    loading.value = false
  }
  //  获取工单列表排序字段设置
  const getTableDataList = async () => {
    loading.value = true
    await getOrderTableOrderByField(type.value).then((res) => {
      if (res) {
        TableDataList.value = res.data.data.rows
      }
    })
    loading.value = false
  }
  // 点击表头 '恢复默认', '全部显示', '全部冻结', '全部解冻', '上移', '下移',首行,末行,'移到'
  // sort越小越往前
  const onClickoptionsHeader = async (n) => {
    if (n == 8) {
      if (!numInput.value) {
        ElMessage({
          message: '请输入行数',
          type: 'warning',
          offset: 200,
        })
        return
      }
    }
    switch (n) {
      case 0:
        loading.value = true
        await getOrderTableInitField().then((res) => {
          if (res) {
            let arr = res.data.data.rows.map((o, index) => {
              return { ...o, sort: index, initFieldName: o.name, admFactoryOrderTableFieldId: o.id }
            })
            let arr2 = JSON.parse(JSON.stringify(HeaderDataList.value))
            HeaderDataList.value = arr.map((i) => {
              arr2.map((o) => {
                if (i.admFactoryOrderTableFieldId == o.admFactoryOrderTableFieldId) {
                  i = { ...i, id: o.id, code: o.code }
                }
              })
              return i
            })
          }
        })
        loading.value = false
        break
      case 1:
        HeaderDataList.value = HeaderDataList.value.map((o) => {
          return { ...o, showColumn: true }
        })
        break
      case 2:
        HeaderDataList.value = HeaderDataList.value.map((o) => {
          return { ...o, freezeColumn: true }
        })
        break
      case 3:
        HeaderDataList.value = HeaderDataList.value.map((o) => {
          return { ...o, freezeColumn: false }
        })
        break
      case 4:
      case 6:
      case 8:
        if (arrSelection.value.length == 0) {
          ElMessage({
            message: '请选择要上移的项',
            type: 'warning',
            offset: 200,
          })
        } else {
          let arr = JSON.parse(JSON.stringify(HeaderDataList.value)) //赋值
          let arrSele = JSON.parse(JSON.stringify(arrSelection.value)) //赋值
          if (n == 8) {
            // 判断是设置下移
            let Siteindex = HeaderDataList.value.findIndex(
              (o) =>
                arrSelection.value[0].admFactoryOrderTableFieldId == o.admFactoryOrderTableFieldId,
            )
            if (numInput.value - 1 > Siteindex) {
              // 判断上移的有等于最大值
              if (arrSele.some((o) => o.sort == arr.length - 1)) {
                ElMessage({
                  message: '移动的项，已到达末尾',
                  type: 'warning',
                  offset: 200,
                })
                return
              }
              for (let index = arr.length - 1; index >= 0; index--) {
                const o = arr[index]
                arrSele = arrSelection.value.map((i) => {
                  if (i.admFactoryOrderTableFieldId == o.admFactoryOrderTableFieldId) {
                    HeaderDataList.value[index].sort = numInput.value - 1
                    let arrItem = HeaderDataList.value[index]
                    HeaderDataList.value.splice(index, 1)
                    HeaderDataList.value.splice(numInput.value - 1, 0, arrItem)
                    i.sort = numInput.value - 1
                  }
                  return i
                })
                HeaderDataList.value[index].sort = index
              }
              multipleTableRef.value!.clearSelection()
              arrSelection.value = []
              numInput.value = null
              popover.value.hide()
              return
            }
          }

          // 判断上移的有等于0
          if (arrSele.some((o) => o.sort == 0)) {
            ElMessage({
              message: '移动的项，已到达首行',
              type: 'warning',
              offset: 200,
            })
            return
          }
          for (let index = 0; index < arr.length; index++) {
            const o = arr[index]
            arrSele = arrSelection.value.map((i) => {
              if (i.admFactoryOrderTableFieldId == o.admFactoryOrderTableFieldId) {
                if (n == 8) {
                  if (index > numInput.value - 1) {
                    HeaderDataList.value[index].sort = numInput.value - 1
                    let arrItem = HeaderDataList.value[index]
                    HeaderDataList.value.splice(index, 1)
                    HeaderDataList.value.splice(numInput.value - 1, 0, arrItem)
                    i.sort = numInput.value - 1
                  }
                }
                if (n == 6) {
                  HeaderDataList.value[index].sort = 0
                  let arrItem = HeaderDataList.value[index]
                  HeaderDataList.value.splice(index, 1)
                  HeaderDataList.value.splice(0, 0, arrItem)
                  i.sort = 0
                } else if (n == 4) {
                  HeaderDataList.value[index].sort = index - 1
                  let arrItem = HeaderDataList.value[index]
                  HeaderDataList.value.splice(index, 1)
                  HeaderDataList.value.splice(index - 1, 0, arrItem)
                  i.sort = i.sort - 1
                }
              }
              return i
            })
            HeaderDataList.value[index].sort = index
          }
          if (n == 8) {
            multipleTableRef.value!.clearSelection()
            arrSelection.value = []
            numInput.value = null
          }
          if (n == 6 || n == 8) {
            popover.value.hide()
          }
        }
        break
      case 5:
      case 7:
        if (arrSelection.value.length == 0) {
          ElMessage({
            message: '请选择要下移的项',
            type: 'warning',
            offset: 200,
          })
        } else {
          let arr = JSON.parse(JSON.stringify(HeaderDataList.value)) //赋值
          let arrSele = JSON.parse(JSON.stringify(arrSelection.value)) //赋值
          // 判断上移的有等于最大值
          if (arrSele.some((o) => o.sort == arr.length - 1)) {
            ElMessage({
              message: '移动的项，已到达末尾',
              type: 'warning',
              offset: 200,
            })
            return
          }
          for (let index = arr.length - 1; index >= 0; index--) {
            const o = arr[index]
            arrSele = arrSelection.value.map((i) => {
              if (i.admFactoryOrderTableFieldId == o.admFactoryOrderTableFieldId) {
                if (n == 8) {
                  if (index < numInput.value - 1) {
                    HeaderDataList.value[index].sort = numInput.value - 1
                    let arrItem = HeaderDataList.value[index]
                    HeaderDataList.value.splice(index, 1)
                    HeaderDataList.value.splice(numInput.value - 1, 0, arrItem)
                    i.sort = numInput.value - 1
                  }
                }
                if (n == 7) {
                  HeaderDataList.value[index].sort = arr.length - 1
                  let arrItem = HeaderDataList.value[index]
                  HeaderDataList.value.splice(index, 1)
                  HeaderDataList.value.splice(arr.length - 1, 0, arrItem)
                  i.sort = arr.length - 1
                } else if (n == 5) {
                  HeaderDataList.value[index].sort = index + 1
                  let arrItem = HeaderDataList.value[index]
                  HeaderDataList.value.splice(index, 1)
                  HeaderDataList.value.splice(index + 1, 0, arrItem)
                  i.sort = i.sort + 1
                }
              }
              return i
            })
            HeaderDataList.value[index].sort = index
          }
          if (n == 7 || n == 8) {
            popover.value.hide()
          }
        }
        break
    }
  }
  // 显示前触发
  const popoverShow = () => {
    if (arrSelection.value.length == 0) {
      ElMessage({
        message: '请选择要移动的项',
        type: 'warning',
        offset: 200,
      })
      popover.value.hide()
    } else if (arrSelection.value.length > 1) {
      ElMessage({
        message: '仅可以选择一项移动',
        type: 'warning',
        offset: 200,
      })
      popover.value.hide()
    }
  }
  // 点击列表设置 '恢复默认', '升序', '降序'
  const onClickoptionsTableData = async (n) => {
    switch (n) {
      case 0:
        loading.value = true
        await getOrderTableInitOrderByField().then((res) => {
          if (res) {
            TableDataList.value = res.data.data.rows.map((o, index) => {
              return { ...o, admOrderByFieldId: o.id, id: null }
            })
          }
        })
        loading.value = false
        break
      case 1:
        if (arrSelection.value.length == 0) {
          ElMessage({
            message: '请选择要升序的项',
            type: 'warning',
            offset: 200,
          })
        } else
          TableDataList.value = TableDataList.value.map((o) => {
            if (arrSelection.value.some((i) => i.admOrderByFieldId == o.admOrderByFieldId)) {
              o.orderBy = 1
            }
            return o
          })
        break
      case 2:
        if (arrSelection.value.length == 0) {
          ElMessage({
            message: '请选择要降序的项',
            type: 'warning',
            offset: 200,
          })
        } else
          TableDataList.value = TableDataList.value.map((o) => {
            if (arrSelection.value.some((i) => i.admOrderByFieldId == o.admOrderByFieldId)) {
              o.orderBy = 2
            }
            return o
          })
        break
    }
  }
  // 保存
  const onSave = async (n) => {
    if (n == 1) {
      loading.value = true
      await workTableFieldSave(HeaderDataList.value, type.value).then((res) => {
        if (res) {
          ElMessage({
            message: res.data.message,
            type: res.data.success ? 'success' : 'error',
          })
          if (res.data.success) {
            onCancel()
            emits('update-list')
          }
        }
      })
      loading.value = false
    }
    if (n == 2) {
      loading.value = true
      await orderBySave(TableDataList.value, type.value).then((res) => {
        if (res) {
          ElMessage({
            message: res.data.message,
            type: res.data.success ? 'success' : 'error',
          })
          if (res.data.success) {
            onCancel()
            emits('update-list')
          }
        }
      })
      loading.value = false
    }
  }

  const dragIndex = ref() //记录移动停放位置index
  // 鼠标移动过程触发
  const dragover = (e: { preventDefault: () => void }) => {
    e.preventDefault()
  }
  // 鼠标不移动时一直触发
  const dragenter = (e: { preventDefault: () => void }, index) => {
    e.preventDefault()
    dragIndex.value = index
  }
  // 鼠标停止触发 index==>被移动的元素下标
  const dragend = (index) => {
    if (dragIndex.value !== index) {
      const moving = HeaderDataList.value[index] // 移动的项
      HeaderDataList.value.splice(index, 1)
      HeaderDataList.value.splice(dragIndex.value, 0, moving)
      HeaderDataList.value = HeaderDataList.value.map((o, index) => {
        return { ...o, sort: index }
      })
    }
  }

  // 选择列表数据
  const handleSelectionChange = (arr) => {
    arrSelection.value = JSON.parse(JSON.stringify(arr))
  }
</script>
<style lang="scss">
  .header_Table {
    display: flex;

    .title_xy {
      margin: 0 12px 12px;
      padding-bottom: 8px;
      cursor: pointer;
      position: relative;
      color: #999;

      &.title_color {
        color: #007cff;

        &::after {
          content: '';
          height: 2px;
          width: 100%;
          box-sizing: border-box;
          background-color: #007cff;
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          margin: 0 auto;
        }
      }

      &:hover {
        color: #007cff;
      }
    }
  }

  :deep(.style_txt) {
    cursor: pointer;
    color: #007cff;
  }

  .list_option {
    display: flex;
    align-items: center;
    justify-content: end;

    .item_option {
      color: #007cff;
      cursor: pointer;
      margin: 0 12px 20px;
    }
  }
</style>
